package feces.servlet;

import java.io.IOException;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import feces.model.ProductMajorType_;
import feces.model.ProductMinorType;
import feces.model.ProductMinorType_;
import feces.utility.Utility;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * 获取所有商品二级分类
 * 
 * @author Bromine0x23
 */
@WebServlet(name = "product_minor_types", urlPatterns = { "/api/product_minor_types" })
@NoArgsConstructor
public class ProductMinorTypesServlet extends RESTfulServlet {

	private static final long serialVersionUID = 4184850032219711886L;

	/**
	 * 字典
	 * 
	 * @author Bromine0x23
	 */
	@NoArgsConstructor(access = AccessLevel.PRIVATE)
	public static final class Dictonary {

		public static final String MAJOR_ID = "major_id";
	}

	/**
	 * 响应GET请求
	 * 可选参数major_id，指定一级分类
	 * 
	 * @return 满足条件的商品二级分类
	 */
	@Override
	protected Response<List<ProductMinorType>> responseRead(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		CriteriaBuilder builder = getCriteriaBuilder();
		CriteriaQuery<ProductMinorType> query = builder.createQuery(ProductMinorType.class);
		Root<ProductMinorType> root = query.from(ProductMinorType.class);
		String parameter = request.getParameter(Dictonary.MAJOR_ID);
		if (parameter != null) {
			Integer id = Utility.toInteger(parameter);
			if (id == null) {
				return invalid(null);
			}
			query.where(
				builder.equal(
					root.get(ProductMinorType_.majorType).get(ProductMajorType_.id), id
				)
			);
		}
		return succeed(executeQuery(query));
	}
}
